package site.luojie.core.annotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

import static site.luojie.utils.StringUtil.toLowerCaseFirstChar;

/**
 * @Description:
 * @Author jie.luo
 * @Create: 2020-05-06 02:43
 **/
public class AnnotationUtil {

    /**
     * 根据 class 和 注解 获取容器中 name
     *
     * @param clazz 业务类
     * @return 容器名
     * 例如：
     * @Service("demo") // 容器中id为demo
     * public class DemoService
     * @Service // 容器中id为 demoService
     * public class DemoService
     */
    public static String getName(Class<?> clazz) {
        String name = "";
        for (Annotation clazzAnnotation : clazz.getAnnotations()) {
            if (clazzAnnotation.annotationType() == Component.class) {
                name = ((Component) clazzAnnotation).value();
            } else if (clazzAnnotation.annotationType() == Service.class) {
                name = ((Service) clazzAnnotation).value();
            } else if (clazzAnnotation.annotationType() == Repository.class) {
                name = ((Repository) clazzAnnotation).value();
            }
        }
        if (null == name || "".equals(name)) {
            name = toLowerCaseFirstChar(clazz.getSimpleName());
        }
        return name;
    }

    /**
     * 判断该类是否开启事务
     *
     * @param clazz 业务类
     * @return true-开启了事务
     */
    public static boolean classContainTransactional(Class<?> clazz) {
        for (Annotation clazzAnnotation : clazz.getAnnotations()) {
            if (clazzAnnotation.annotationType() == Transactional.class) {
                return true;
            }
        }

        Method[] methods = clazz.getMethods();
        for (Method method : methods) {
            Annotation[] declaredAnnotations = method.getDeclaredAnnotations();
            for (Annotation declaredAnnotation : declaredAnnotations) {
                if (declaredAnnotation.annotationType() == Transactional.class) {
                    return true;
                }
            }
        }

        return false;
    }

}
